import AMapLoader from '@amap/amap-jsapi-loader';
import type { MapRes, PlaceSearch, SearchPage, GeocoderRes } from './types';

const mapKey = import.meta.env.ENV_AMAP_KEY;
const mapCode = import.meta.env.ENV_AMAP_CODE;


// 初始化地图
export const initAMap = async (el: HTMLDivElement | null) => {
  // @ts-ignore
  window._AMapSecurityConfig = {
    securityJsCode: mapCode,
  };

  const AMap = await AMapLoader.load({
    key: mapKey,
    version: "2.0",

    plugins: ["AMap.PlaceSearch"],
  });

  const map = new AMap.Map(el, {
    zoom: 11,
    viewMode: "3D",
    center: [116.397428, 39.90923],
  });

  return {
    map,
    AMap,
    destroy: () => map.destroy()
  } as MapRes;
}

export const initSearch = (res: MapRes) => (
  new Promise<PlaceSearch>(resolve => {
    const opts = {
      panel: false,
      map: res.map,
      pageSize: 6,
      pageIndex: 1,
      citylimit: true,
      autoFitView: true,
    }
    res.AMap.plugin(["AMap.PlaceSearch"], () => {
      resolve(new res.AMap.PlaceSearch(opts));
    });
  })
);

// 根据关键字检索
export const searchByKeywords = (
  keywords: string,
  search: PlaceSearch,
) => new Promise<SearchPage>((resolve, reject) => (
  search.search(keywords, (status, res) => {
    if (status === 'complete') {
      const po = res.poiList;
      const data = po?.pois || [];
      resolve([data, {
        total: po.count,
        current: po.pageIndex,
        pageSize: po.pageSize,
      }]);
    } else {
      reject(new Error('获取数据失败！'));
    }
  })
));

export const initGeocoder = (res: MapRes) => (
  new Promise<GeocoderRes>(resolve => {
    res.AMap.plugin('AMap.Geocoder', function () {
      const instace = new res.AMap.Geocoder({});
      resolve(instace);
    });
  })
);

export const getAddressByPos = async (res: MapRes, pos: number[]) => {
  const evt = await initGeocoder(res);
  return new Promise(resolve => {
    evt.getAddress(pos, (status, res) => {
      resolve(res);
    });
  })
}

export const setCenterByPos = (
  res: MapRes,
  pos: number[],
  zoom: number = 20
) => res.map.setZoomAndCenter(zoom, pos);